package com.hwadee.property.util;

import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.*;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;

@Component
public class FileUtil {

    // 允许上传的文件类型
    private static final List<String> ALLOWED_FILE_TYPES = Arrays.asList(
            "image/jpeg", "image/jpg", "image/png", "application/pdf", "text/plain"
    );

    // 允许的文件扩展名
    private static final List<String> ALLOWED_EXTENSIONS = Arrays.asList("jpg", "jpeg", "png", "gif", "txt");

    // 上传目录路径
    private static final Path UPLOAD_THUMBNAIL_DIR = Paths.get("C:\\uploads\\thumbnail");
    private static final Path UPLOAD_COMPLAIN_DIR = Paths.get("C:\\uploads\\complain");
    private static final Path UPLOAD_NOTICE_DIR = Paths.get("C:\\uploads\\notice");
    private static final Path UPLOAD_CHARGE_ITEM_DIR = Paths.get("C:\\uploads\\charge_item");

    // 文件大小限制（1MB）
    private static final long MAX_FILE_SIZE = 1024 * 1024;

    // 上传文件并获取保存路径
    public String uploadFileAndGetPath(MultipartFile multipartFile, String fileType) {
        // 检查文件是否为空
        if (multipartFile == null || multipartFile.isEmpty()) {
            throw new IllegalArgumentException("文件为空，请选择一个文件上传");
        }

        // 检查文件大小
        if (multipartFile.getSize() > MAX_FILE_SIZE) {
            throw new IllegalArgumentException("文件大小超出限制（最大 " + MAX_FILE_SIZE / (1024 * 1024) + "MB）");
        }

        // 检查文件类型
        String contentType = multipartFile.getContentType();
        if (contentType == null) {
            throw new IllegalArgumentException("无法获取文件的类型，请确保上传的文件是有效的");
        } else if (!isFileTypeAllowed(contentType)) {
            throw new IllegalArgumentException("不允许上传的文件类型：" + contentType);
        }

        // 处理文件（保存到本地目录）
        Path uploadDir = setDir(fileType);

        File uploadPath = uploadDir.toFile();
        if (!uploadPath.exists()) {
            uploadPath.mkdirs();
        }

        // 生成唯一的文件名，避免文件名冲突
        String originalFilename = multipartFile.getOriginalFilename();
        String fileExtension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }
        String uniqueFileName = UUID.randomUUID().toString() + fileExtension;

        Path targetFilePath = uploadDir.resolve(uniqueFileName);
        try {
            // 使用 transferTo 方法直接保存文件
            multipartFile.transferTo(targetFilePath.toFile());
            return targetFilePath.toString();
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败：" + e.getMessage(), e);
        }
    }

    // 检查文件类型是否允许
    private boolean isFileTypeAllowed(String contentType) {
        return ALLOWED_FILE_TYPES.contains(contentType);
    }

    private Path setDir(String fileType) {
        if (fileType == null) {
            throw new IllegalArgumentException("File type cannot be null.");
        }

        switch (fileType) {
            case "thumbnail":
                return UPLOAD_THUMBNAIL_DIR;
            case "complain":
                return UPLOAD_COMPLAIN_DIR;
            case "notice":
                return UPLOAD_NOTICE_DIR;
            case "charge_item":
                return UPLOAD_CHARGE_ITEM_DIR;
            default:
                throw new IllegalArgumentException("Unsupported file type: " + fileType);
        }
    }

    // 检查文件是否存在并进行安全验证
    public String checkIfExist(String path, String fileType) {
        Path uploadDir = setDir(fileType);

        if (path == null || path.isEmpty()) {
            return null;
        }

        // 获取上传目录的绝对路径
        Path uploadPath = uploadDir.toAbsolutePath().normalize();

        // 获取文件的绝对路径
        Path filePath = uploadPath.resolve(path).normalize();

        // 检查文件路径是否在上传目录内
        if (!filePath.startsWith(uploadPath)) {
            throw new SecurityException("非法路径访问：" + path);
        }

        // 检查文件扩展名是否允许
        String fileExtension = getFileExtension(path);
        if (!ALLOWED_EXTENSIONS.contains(fileExtension.toLowerCase())) {
            throw new IllegalArgumentException("不允许的文件类型：" + fileExtension);
        }

        // 检查文件是否存在
        File file = filePath.toFile();
        if (file.exists() && file.isFile()) {
            return filePath.toString();
        } else {
            return null;
        }
    }

    // 获取文件扩展名
    public String getFileExtension(String fileName) {
        if (fileName == null || fileName.isEmpty()) {
            return "";
        }

        int dotIndex = fileName.lastIndexOf('.');
        if (dotIndex > 0 && dotIndex < fileName.length() - 1) {
            return fileName.substring(dotIndex + 1);
        }
        return "";
    }

    // 删除指定路径的文件
    public void deleteOldFile(String path, String fileType) {
        if (path == null || path.isEmpty()) {
            throw new IllegalArgumentException("文件路径不能为空");
        }

        Path filePath = Paths.get(path).toAbsolutePath().normalize();

        // 验证路径是否在允许的目录内
        Path uploadPath = setDir(fileType).toAbsolutePath().normalize();
        if (!filePath.startsWith(uploadPath)) {
            throw new SecurityException("非法路径访问：" + path);
        }

        File file = filePath.toFile();
        if (file.exists()) {
            if (file.delete()) {
                System.out.println("文件删除成功：" + path);
            } else {
                throw new RuntimeException("文件删除失败：" + path);
            }
        } else {
            throw new IllegalArgumentException("文件不存在，无法删除：" + path);
        }
    }

    // 返回文件的 InputStream
    public FileInputStream getFileInputStream(String path) {
        if (path == null || path.isEmpty()) {
            throw new IllegalArgumentException("文件路径不能为空");
        }

        File file = new File(path);
        if (!file.exists() || !file.isFile()) {
            throw new IllegalArgumentException("文件不存在或路径无效：" + path);
        }

        try {
            return new FileInputStream(file);
        } catch (IOException e) {
            throw new RuntimeException("读取文件失败：" + e.getMessage(), e);
        }
    }

    // 获取文件名
    public String getFileName(String path) {
        if (path == null || path.isEmpty()) {
            throw new IllegalArgumentException("文件路径不能为空");
        }

        File file = new File(path);
        return file.getName();
    }
}
